package com.jysz.certificate.web.action.cm;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jysz.certificate.action.AbstractBaseAction;
import com.jysz.certificate.constant.OperCodeConstant;
import com.jysz.certificate.persistence.enums.CertificateStatus;
import com.jysz.certificate.persistence.enums.CertificationType;
import com.jysz.certificate.persistence.enums.CopyOfCertificationImporting;
import com.jysz.certificate.persistence.enums.PostType;
import com.jysz.certificate.persistence.enums.WorkflowOperateType;
import com.jysz.certificate.persistence.enums.WorkflowState;
import com.jysz.certificate.persistence.enums.WorkflowType;
import com.jysz.certificate.persistence.model.cm.Certificate;
import com.jysz.certificate.persistence.model.cm.CertificateRenew;
import com.jysz.certificate.persistence.model.cm.Certification;
import com.jysz.certificate.persistence.model.cm.CertificationDTO;
import com.jysz.certificate.persistence.model.cm.RecordReturn;
import com.jysz.certificate.persistence.model.system.Brand;
import com.jysz.certificate.persistence.model.system.Financial;
import com.jysz.certificate.persistence.model.system.Organization;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.persistence.model.system.Treaty;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.persistence.model.workflow.Workflow;
import com.jysz.certificate.service.cm.CertificateService;
import com.jysz.certificate.service.cm.CertificationService;
import com.jysz.certificate.service.cm.RecordReturnService;
import com.jysz.certificate.service.core.AttachmentService;
import com.jysz.certificate.service.system.BrandService;
import com.jysz.certificate.service.system.FinancialService;
import com.jysz.certificate.service.system.OrganizationService;
import com.jysz.certificate.service.system.ShopService;
import com.jysz.certificate.service.system.TreatyService;
import com.jysz.certificate.service.system.UserService;
import com.jysz.certificate.service.workflow.WorkflowService;
import com.jysz.certificate.utils.CommonUtil;
import com.jysz.certificate.utils.PoiUtils;
import com.jysz.certificate.web.action.Excel.ExcelSheetParser;
import com.jysz.webcore.ssh.annotation.PermissionPoint;

@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Namespace("/cm")
public class CertificationAction extends AbstractBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private final static Logger LOG = LoggerFactory.getLogger(CertificationAction.class);
	@Resource
	private AttachmentService attachmentService;
	@Resource
	private CertificationService cfService;// 合格证核心Service
	@Resource
	private BrandService brandService;// 主机厂service
	@Resource
	private FinancialService financialService;// 金融机构service
	@Resource
	private TreatyService treatyService;//协议service
	@Resource
	private ShopService shopService;// 销售店Service
	@Resource
	private CertificateService certificateService;
	@Resource
	private WorkflowService workflowService;// 流程
	@Resource
	private OrganizationService organizationService;
	@Resource
	private UserService userService;
	@Resource
	private RecordReturnService recordReturnService;
	
	private String brandId;
	private Long shopIdLong;// 店铺ID
	private Long id;// 合格证Id
	private Certification cerF;// 合格证实体
	private Brand brand;// 主机厂
	private List<Brand> brandList;
	private Shop shopSc;
	private Shop shopDTO;
	private List<Shop> shopList;
	private List<Treaty> treaties;//协议
	private Certification cre;
	private Workflow workflow;//释放单关联的流程
	private Integer caozuo;
	private Long userId;
	private Financial financial;// 金融机构
	private String markShop;
	private String msg;
	private List<Financial> fiList;
	private File file;
	private Integer flag;
	private Certificate c;
	private Certification cer;
	private CertificationDTO search;
	private List<Shop> shops;
	private String ids;
	private String vals;
	private float price;
	private Certification entity;
	
	private List<RecordReturn> recordReturn;
	
	private Integer indexA;
	private String userName;//用户名
	private String returnRemark;
	
	public String getUserName() {
		return userName;
	}

	public String getReturnRemark() {
		return returnRemark;
	}

	public void setReturnRemark(String returnRemark) {
		this.returnRemark = returnRemark;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
 

	public String getMarkShop() {
		return markShop;
	}

	public void setMarkShop(String markShop) {
		this.markShop = markShop;
	}

	public String getBrandId() {
		return brandId;
	}

	public void setBrandId(String brandId) {
		this.brandId = brandId;
	}

	public Workflow getWorkflow() {
		return workflow;
	}

	public void setWorkflow(Workflow workflow) {
		this.workflow = workflow;
	}

	public Certification getEntity() {
		return entity;
	}

	public void setEntity(Certification entity) {
		this.entity = entity;
	}

	public Integer getFlag() {
		return flag;
	}

	public void setFlag(Integer flag) {
		this.flag = flag;
	}

	public List<Shop> getShops() {
		return shops;
	}

	public void setShops(List<Shop> shops) {
		this.shops = shops;
	}
	@Action("show")
	public String show(){
		if(c==null||c.getId()==null){
			setSuccessPopMessage("缺少必要参数ID,请重新尝试");
			setRedirectUrl("index.do?currentPage="+getCurrentPage());
			return SHOW_MSG_PAGE;
		}
		c = certificateService.find(c.getId());
		cer = cfService.find(c.getCertification().getId());
		workflow=workflowService.find(WorkflowType.UPDATE, c.getId());
		setRedirectUrl(getContextPath()+"/cm/show.do?c.id="+c.getId());
		return "show";
	}

	@SuppressWarnings("rawtypes")
	@Action("exportStore")
	public String exportStore() {
//		brandList = brandService.findAll();
//		fiList = financialService.findAll();
		if (brand != null) {
			Set<Brand> list = new HashSet<Brand>();
			list.add(brand);
			if(null == shopDTO){
				shopDTO = new Shop();
			}
			shopDTO.setBrands(list);
		}
		Long financialId = null;
		if(financial != null){
			financialId = financial.getId();
		}
		
		List<Map> shops = shopService.findStoreCount(shopDTO,brand, financialId, userId);

		//collection.{expression}取集合对象属性
		String[] headers = {"店号", "经销商名称", "库存数量", "对应厂家", "驻店员","区域经理"};
		String[] columns = {"shop.shopMark", "shop.shopName", "cfCount", "#cfa.getBrandsByShop(shop)", "#cfa.findUserShopByShopId(shop.id)", "#cfa.getShopUserName(shop.id)"};
		HttpServletResponse response = this.getResponse();
	    response.setContentType("octets/stream");
	    response.addHeader("Content-Disposition",
	                "attachment;filename=" + toUtf8Encode("库存清单") + ".xls");
		OutputStream out = null;
		try {
			out = this.getResponse().getOutputStream();
			Map<String, Object> context = new HashMap<String, Object>();
			context.put("cfa", this);
			PoiUtils.exportExcel("库存清单", headers, columns, shops, out, null, context);
		} catch (Exception e) {
			LOG.error("导出库存清单出错。。。", e);
		}
		
		return null;
	}
	public String getBrandsByShop(Shop shop){
		Set<Brand> brands = shop.getBrands();
		
		if(brands == null){
			return "";
		}
		
		StringBuilder builder = new StringBuilder();
		for (Iterator<Brand> iterator = brands.iterator(); iterator.hasNext();) {
			Brand brand = iterator.next();
			builder.append(brand.getName());
			
			if(iterator.hasNext()){
				builder.append(",");
			}
		}
		
		return builder.toString();
	}
	
	public String getStatusStr(Certification entity){
		return StringUtils.isNotBlank(entity.getTheAddress()) && CertificationType.INSTOCK.equals(entity.getState()) ? "在库(二网)" : entity.getState().getName();
	}
	
	@Action("export")
	public String export() {
		List<Certification> cfs = cfService.findCfs(search);

		String[] headers = {"序号", "店号", "店名","渠道","金融机构","合格证号", "车型", "车架号", "状态", "供货价", "订单号",
				"汇票号", "出门日", "预定到店日",   "入库时间", "出库时间", "汇票启始日期","汇票结束日期", "发动机号"};
		String[] columns = {"#index", "shop.shopMark", "shop.shopName","brand.name","financial.name","certificationNum", "motorcycleType", "chassis", "#cfa.getStatusStr(#cf)", "supplyPrice", "orderNumber",
				"draft", "goingOutDate", "scheduledDate","@com.jysz.certificate.utils.DateUtil@formatDate(warehouseDate,'yyyy-MM-dd')", "@com.jysz.certificate.utils.DateUtil@formatDate(leaveDate,'yyyy-MM-dd')", "@com.jysz.certificate.utils.DateUtil@formatDate(draftBeginDate,'yyyy-MM-dd')","@com.jysz.certificate.utils.DateUtil@formatDate(draftEndDate,'yyyy-MM-dd')","engine" };
		HttpServletResponse response = this.getResponse();
	    response.setContentType("octets/stream");
	    response.addHeader("Content-Disposition",
	                "attachment;filename=" + toUtf8Encode("合格证") + ".xls");
		OutputStream out = null;
		try {
			
			out = this.getResponse().getOutputStream();
			Map<String, Object> context = new HashMap<String, Object>();
			context.put("cfa", this);
			PoiUtils.exportExcel("合格证", headers, columns, cfs, out, null, context,"cf");
		} catch (Exception e) {
			LOG.error("导出合格证出错。。。", e);
		}
		
		return null;
	}
	
	@Action("toUpdate")
	@PermissionPoint(point=OperCodeConstant.CM_CER_UPDATE)
	public String toUpdate() {
		c = certificateService.getUpdateCertificate(cer.getId(),CertificateStatus.NOTSTART);
		cer = cfService.getCertification(cer.getId());
		fiList = treatyService.getFinanList(cer.getShop().getId());
		if(c==null){
			c = beanCopyCertification(cer, new Certificate());
		}
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",
				search);
		return "update";
	}
	
	@Action("toTeUpdate")
	@PermissionPoint(point=OperCodeConstant.CM_CER_UPDATE)
	public String toTeUpdate() {
		c = certificateService.getUpdateCertificate(cer.getId(),CertificateStatus.NOTSTART);
		cer = cfService.getCertification(cer.getId());
		fiList = treatyService.getFinanList(cer.getShop().getId());
		if(c==null){
			c = beanCopyCertification(cer, new Certificate());
		}
		setRedirectUrl("update/index.do?currentPage=" + getCurrentPage(), "search",
				null);
		return "update";
	}
	
	//驻店员只能修改
	public boolean getUpdateCertificate(Long id) {
		if(PostType.Shop.equals(getUser().getPost())){
			c = certificateService.getUpdateCertificate(id,
					CertificateStatus.SUBMITED);//查询这个合格证是否正在提交修改。
			cer = cfService.getCertification(id);
			boolean pass = c==null?true:false;
			boolean pass1 = cer.getCmImporting()==CopyOfCertificationImporting.YES?false:true;
			return pass&&pass1;
		}else if(PostType.RESTS.equals(getUser().getPost())||PostType.Manager.equals(getUser().getPost())){
			return false;
		}else
			return true;
	}

	@Action("updateSave")
	@PermissionPoint(point=OperCodeConstant.CM_CER_UPDATE)
	public String updateSave() {
		Certificate ce = certificateService.getUpdateCertificate(c.getCertification().getId(),CertificateStatus.NOTSTART);
		if(ce!=null){
			c.setId(ce.getId());
		}
		if (!certificateService.getCertifite(c)) {
			setSuccessPopMessage("车型或合格证号已存在无法修改.");
		}else if(!cfService.getCertifition(c)){ 
			setSuccessPopMessage("已有改车型或合格证号的修改单,无法修改.");
		}else if(certificateService.getUpdateCertificate(c.getCertification().getId(),CertificateStatus.SUBMITED)!=null){
			setSuccessPopMessage("该合格证修改单正在审核中...");
		}else {
			c.setStatus(CertificateStatus.NOTSTART);
			setSuccessPopMessage("保存成功");
			certificateService.merge(c);
			c = certificateService.getUpdateCertificate(c.getCertification()
					.getId(), CertificateStatus.NOTSTART);
		}
		return SHOW_MSG_PAGE;
	}

	@Action("updateSubmit")
	@PermissionPoint(point=OperCodeConstant.CM_CER_UPDATE)
	public String updateSubmit() {
		Certificate ce = certificateService.getUpdateCertificate(c.getCertification().getId(),CertificateStatus.NOTSTART);
		if(ce!=null){
			c.setId(ce.getId());
		}
		if (!certificateService.getCertifite(c)) {
			setSuccessPopMessage("车型或合格证号已存在无法修改.");
		}else if(!cfService.getCertifition(c)){ 
			setSuccessPopMessage("已有改车型或合格证号的修改单,无法修改.");
		}else if(certificateService.getUpdateCertificate(c.getCertification().getId(),CertificateStatus.SUBMITED)!=null){
			setSuccessPopMessage("该合格证修改单正在审核中...");
		}else {
			if(PostType.Shop.equals(getUser().getPost())){
				c.setStatus(CertificateStatus.SUBMITED);
				setSuccessPopMessage("提交成功,待审核...");
				certificateService.merge(c);
				c = certificateService.getUpdateCertificate(c.getCertification()
						.getId(), CertificateStatus.SUBMITED);
				// 调流程
				
				Workflow w = workflowService.find(WorkflowType.UPDATE, id);
				if(w != null){//判断是否存在该流程！
					workflowService.audit(getUser(), w, WorkflowState.SUBMITED, WorkflowOperateType.SUBMIT, c.getReson());
				}else{
					workflowService.addWorkflow(getUser(), c.getId(),WorkflowState.SUBMITED, WorkflowType.UPDATE,Certificate.class, c.getReson());
				}
				
			}else{
				c.setStatus(CertificateStatus.FINISH);
				setSuccessPopMessage("修改成功");
				certificateService.merge(c);
				cer = cfService.getCertification(c.getCertification().getId());
				cer = beanCopy(cer, c);
				cfService.merge(cer);
			}
		}
		return SHOW_MSG_PAGE;
	}
	
	public Certification beanCopy(Certification cer,Certificate c){
		cer.setBrand(c.getBrand());
		cer.setFinancial(c.getFinancial());
		cer.setDraft(c.getDraft());
		cer.setOrderNumber(c.getOrderNumber());
		cer.setMotorcycleType(c.getMotorcycleType());
		cer.setGoingOutDate(c.getGoingOutDate());
		cer.setChassis(c.getChassis());
		cer.setScheduledDate(c.getScheduledDate());
		cer.setCertificationNum(c.getCertificationNum());
		cer.setSupplyPrice(c.getSupplyPrice());
		cer.setDraftBeginDate(c.getDraftBeginDate());
		cer.setDraftEndDate(c.getDraftEndDate());
		return cer;
	}
	
	public Certificate beanCopyCertification(Certification c,Certificate cer){
		cer.setBrand(c.getBrand());
		cer.setFinancial(c.getFinancial());
		cer.setDraft(c.getDraft());
		cer.setOrderNumber(c.getOrderNumber());
		cer.setMotorcycleType(c.getMotorcycleType());
		cer.setGoingOutDate(c.getGoingOutDate());
		cer.setChassis(c.getChassis());
		cer.setScheduledDate(c.getScheduledDate());
		cer.setCertificationNum(c.getCertificationNum());
		cer.setSupplyPrice(c.getSupplyPrice()==null?0:c.getSupplyPrice());
		cer.setDraftBeginDate(c.getDraftBeginDate());
		cer.setDraftEndDate(c.getDraftEndDate());
		return cer;
	}

	@Action("toImport")
	public String toImport() {
		brandList = brandService.seleteAll();
		fiList = financialService.finList();
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
		return "import";
	}

	@Action(ADD)
	public String add() {
		brandList = brandService.findAll();
		fiList = financialService.findAll();
		
		if(PostType.Shop.equals(getUser().getPost())){
			StringBuilder names = new StringBuilder();
			 List<Organization> orgs = organizationService.findShopsByCurrentUser();
			 shops = new ArrayList<Shop>();
			 if(orgs != null && orgs.size() > 0){
					for (Iterator<Organization> iterator = orgs.iterator(); iterator.hasNext();) {
						Organization org = iterator.next();
						names.append(org.getName());
						Shop shop = shopService.find(org.getObjectId());
						shops.add(shop);
					}
				}
		}
		cre = new Certification();
		cre.setBuluDate(new Date());
		cre.setScheduledDate(new Date());
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
		return ADD;
	}

	/*
	 * 补录合格证
	 */
	@Action("save")
	public String save() {
		Shop shop = new Shop();
		Certification certification = new Certification();
		User user = this.getUser();
		shop.setId(shopIdLong);
//		cerF.setBrand(getBrand());
		cerF.setFinancial(getFinancial());
		cerF.setShop(shop);
		cerF.setCreateDate(new Date());// 添加创建时间
		cerF.setCmImporting(CopyOfCertificationImporting.NO);// 导入标记
		cerF.setDepartDate(cerF.getBuluDate());
		if (PostType.Shop.equals(user.getPost())) {
			cerF.setState(CertificationType.APPROVED);// 合格证状态，此为驻店员补录，待审核
		} else {
			cerF.setState(CertificationType.ONORDER);// 合格证状态，此为监管科补录，  在途
		}
		String ary[]=null;
		if(cerF.getId() != null){
			certification = cfService.find(cerF.getId());
			ary=new String[]{"id","createdAt","creator","createDate"};
		}else{
			cerF.setCreateDate(new Date());// 添加创建时间
			ary=new String[]{"id","createdAt","creator"};
		}
		
		BeanUtils.copyProperties(cerF,certification, ary);
		try {
//			certification.setGoingOutDate(certification.getBuluDate());//-------添加出门日    出门日=补录日期
			if(certification.getCertificationNum() == null || !StringUtils.isNotBlank(certification.getCertificationNum())){
				certification.setCertificationNum(null);
			}
			cfService.save(certification);
			setSuccessPopMessage("新增数据成功");
		} catch (Exception e) {
			setSuccessPopMessage("合格证补录失败");
		}
		
		Long id = certification.getId();
		if (PostType.Shop.equals(user.getPost())) {//驻店员补录需要发起一个流程
			if (id != 0 && !certification.equals(CertificationType.ONORDER)) {// 判断是否添加成功，，成功则发起新的流程
				Workflow w= workflowService.find(WorkflowType.ADD, id);
				if(w!=null){//判断是否存在该流程！
				workflowService.audit(getUser(), w, WorkflowState.SUBMITED, WorkflowOperateType.SUBMIT, "该证被退回");
				}else{
					if(!StringUtils.isNotBlank(msg)){
						msg = "补录审核流程";
					}
				workflowService.addWorkflow(getUser(), id, WorkflowState.SUBMITED, WorkflowType.ADD, Certification.class, msg );
				}
			}
		}
		
		
		return SHOW_MSG_PAGE;
	}

	@Action("saveb")
	public String saveb() {
		Certification certification =new Certification();
		Shop shop = new Shop();
		shop.setId(shopIdLong);
//		cerF.setBrand(getBrand());
		cerF.setFinancial(getFinancial());
		cerF.setShop(shop);
		cerF.setCmImporting(CopyOfCertificationImporting.NO);// 导入标记
		cerF.setState(CertificationType.UNFINISHED);// 合格证状态，此为未完成的状态，
		String ary[]=null;
		if(cerF.getId() != null){
			certification = cfService.find(cerF.getId());
			ary=new String[]{"id","createdAt","creator","createDate"};
		}else{
			cerF.setCreateDate(new Date());// 添加创建时间
			ary=new String[]{"id","createdAt","creator"};
		}
		
		BeanUtils.copyProperties(cerF,certification, ary);
		try {
			if(certification.getCertificationNum() == null || !StringUtils.isNotBlank(certification.getCertificationNum())){
				certification.setCertificationNum(null);
			}
//			certification.setGoingOutDate(certification.getBuluDate());//-------添加出门日    出门日=补录日期
			cfService.save(certification);
			setSuccessPopMessage("保存数据成功");
		} catch (Exception e) {
			setSuccessPopMessage("保存数据失败");
		}
		return SHOW_MSG_PAGE;
	}

	@Action("detail")
	public String detail() {
		cre = cfService.find(id);
		brandList = brandService.findAll();
		fiList = financialService.findAll();
		if(PostType.Shop.equals(getUser().getPost())){
			StringBuilder names = new StringBuilder();
			 List<Organization> orgs = organizationService.findShopsByCurrentUser();
			 shops = new ArrayList<Shop>();
			 if(orgs != null && orgs.size() > 0){
					for (Iterator<Organization> iterator = orgs.iterator(); iterator.hasNext();) {
						Organization org = iterator.next();
						names.append(org.getName());
						Shop shop = shopService.find(org.getObjectId());
						shops.add(shop);
					}
				}
		}
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",
				search);
		return "add";
	}
	
	@Action("delete")
	public String delete(){
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
		try {
			cfService.destory(id);
			Workflow workflow =workflowService.find(WorkflowType.ADD, id);
			if(null != workflow){
				workflowService.destory(workflow.getId());
			}
			setSuccessPopMessage("删除成功");
		} catch (Exception e) {
			setSuccessPopMessage("删除成功");
		}
		return SHOW_MSG_PAGE;
	}
	
	/**回库*/
	@Action("returnTo")
	public String returnTo() {
		Certification certification=cfService.find(id);
		certification.setTheAddress(null);
		certification.setApplyTheDate(null);
		cfService.save(certification);
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
		setSuccessPopMessage("合格证回库成功");
		return SHOW_MSG_PAGE;
	}

	/*
	 * 补录审核
	 */
	@Action("verify")
	public String verify() {
		cerF = cfService.find(id);
		if(null != flag && flag==1){
			setRedirectUrl(getContextPath()+"/workflow/index.do?currentPage="+getCurrentPage(), "search", search);
		}else{
			setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",search);
		}
		workflow = workflowService.find(WorkflowType.ADD, id);
		return "verify";
	}
	/**
	 * 审核详情
	 * @return
	 */
	@Action("view")
	public String view(){
		if(entity==null||entity.getId()==null){
			setSuccessPopMessage("缺少必要参数ID,请重新尝试");
			setRedirectUrl("index.do?currentPage="+getCurrentPage());
			return SHOW_MSG_PAGE;
		}
		entity=cfService.find(entity.getId());
//		attachs=attachmentService.findAll(entity.getId(),AttachmentType.RELEASE);
		setWorkflow();
		setRedirectUrl(getContextPath()+"/cm/release/view.do?entity.id="+entity.getId());
		return "view";
	}
	private void setWorkflow(){
		workflow=workflowService.find(WorkflowType.ADD, entity.getId());
	}

	@Action("addVerify")
	public String addVerify() {
		Certification c = cfService.find(id);
		if (caozuo == 1) {
			c.setState(CertificationType.INSTOCK);
			c.setWarehouseDate(new Date());
			cfService.save(c);
			workflowService.audit(getUser(), workflowService.find(WorkflowType.ADD, id), WorkflowState.FINISH, WorkflowOperateType.PASS, msg);
		} else {
			c.setState(CertificationType.FILL);
			cfService.save(c);
			workflowService.audit(getUser(), workflowService.find(WorkflowType.ADD, id), WorkflowState.REFUSED, WorkflowOperateType.REFUSE, msg);
		}
		setSuccessPopMessage("数据更新成功");
		return SHOW_MSG_PAGE;
	}

	/*
	 * 导入合格证
	 */
	@SuppressWarnings("rawtypes")
	@Action("importSearch")
	public String importSearch() {
		boolean mark = true;
		boolean ms = true;
		SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
		String DateF = dft.format(new Date());
		Financial finan = financialService.find(financial.getId());
		int xuhao = cfService.batchNumber();
		String batchNum = finan.getBrief() + DateF + (xuhao+1);
		List<Certification> listC = new ArrayList<Certification>();//记录不需要覆盖跟新的合格证
		List<Certification> certifications = new ArrayList<Certification>();//记录需要覆盖跟新的合格证
		Map<String, Certification> certificationMap = null;
		
		try {
			ExcelSheetParser parser = new ExcelSheetParser(file);
			List<List> datas = parser.getDatasInSheet(0);
			if(datas.size() == 0){
				brandList = brandService.seleteAll();
				fiList = financialService.finList();
				this.addActionError("没有可导入的数据");
				 mark = false;
				setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
				return "import";
			}
			List listB = datas.get(0);
			
			 String table = "销售店代码,销售店名称,车型,车架号,订单号,供货价,汇票号,出门日,预定到店日,发车信息日期";
			 String[] ta = table.split(",");
			for(int i=0; i < listB.size(); i++){
				if(ta.length+1!=listB.size()){
					this.addActionError("文件不匹配, 请确认导入文件是合格证导入文件\n");
					 mark = false;
					 break;
				}
				if(i!=listB.size()-1){
					String values=String.valueOf(listB.get(i));
					if(!ta[i].equals(values)){
						this.addActionError("第1行，第"+(i+1)+"列,导入文件表头存在错误\n");
						 mark = false;
						   continue;
					}
				}
			}
			
			List<String> chassises = this.findUniqueChassises(datas);
			
			List<Shop> shops = shopService.findAll();
			Map<String, Organization> map = organizationService.organizationShopMap();
		    certificationMap = cfService.certificationChassisEq(chassises);//暂存 ，在途，待审核，未通过 的所有合格证
			Map<String, Certification> certificationMapNot = cfService.certificationMapNot(chassises);//除 暂存 ，在途，待审核，未通过 的所有合格证
			
			Map<String,Treaty> treatyFinancialMap = treatyService.treatyAllMap(true);//获得所有有效地 协议     键   为金融机构的  名称
			
			Certification c = null;
			if(mark){
			for (int i = 1; i < datas.size(); i++) {// 显示数据
				boolean boo = true;
				List row = datas.get(i);
				Shop shop = null;
				c = new Certification();
				boolean bool = false;//标示是否需要覆盖的
				if(row.size() <= 4){
					this.addActionError("第" + (i + 1) + "行,数据不完善，请检查\n");
					mark = false;
					continue;
				}
				for (int j = 0; j < row.size(); j++) {
					String name = null;
					name = String.valueOf(row.get(j));
					
					
					if (j == 0 && !name.equals("null")) {
						//FIXME: 一次循环组装成hashmap
						for(Shop s : shops){
							boolean bo=false;
							name = name.trim();
							name = name.toUpperCase();
							if(s.getShopMark().equals(name)){// 查找店号是否在库
								shop=s;
									if(treatyFinancialMap.containsKey(shop.getShopName()+"-"+finan.getName())){//判断是否存在协议
										 bo=true;
										 break;
									}
								if(bo==false){
									this.addActionError("第" + (i + 1) + "行，第" + (j + 1)+"列,没有存在与之相符的协议");
									boo = false;//----
									
								}
								break;
							}
						}
						if (shop != null) {
							c.setShop(shop);
						} else {
							this.addActionError("第" + (i + 1) + "行，第" + (j + 1)+ "列," + name + "店号不存在\n");
//							mark = false;
							boo = false;//----
							continue;
						}
					} else if (j == 1 && !name.equals("null")) {
						if (shop != null) {
							if(null != map && map.containsKey(shop.getShopName())){
								
							}else{
								this.addActionError("第" + (i + 1) + "行，第" + (j + 1) + "列,店名:" + shop.getShopName() + " 没有存在组织架构上\n");
//								mark = false;
								boo = false;//----
								continue;
							}
						}
					} else if (j == 2 ) {
						if(name.equals("null")){
							c.setMotorcycleType(null);
						}else{
							c.setMotorcycleType(name);
						}
						
					} else if (j == 3 && !name.equals("null")) {
						name = name.toUpperCase();
						name = name.trim();
//						Certification certification = cfService.certificationChassisKey(name);//判断合格证是否在库
						if(name.length() != 17){
							this.addActionError("第" + (i + 1) + "行，第" + (j + 1) + "列, " + name + "：车架号不符合规范\n");
							mark = false;
							continue;
						}
						if(null != certificationMap && certificationMap.containsKey(name)){//暂存 ，在途，待审核，未通过 的所有合格证   有责更新数据  状态设置为在途
							bool = true;
							
						}else if (null != certificationMapNot && certificationMapNot.containsKey(name)) {// 判断车架号是否已在库
							this.addActionError("第" + (i + 1) + "行，第" + (j + 1)+ "列, " + name + "：车架号已存在\n");
							mark = false;
							continue;
						} else {
							for (int p = 0; p < listC.size(); p++) {// 判断导入文件是否存在相同的车架号
								Certification cfation = listC.get(p);
								if (cfation.getChassis() == name) {
									this.addActionError("导入文件中 第" + (i + 1)+ "行，第" + 4 + "列, " + name+ "：车架号与第" + (p + 2) + "行 第4列"+ cfation.getChassis()+ "  车架号重复\n");
									mark = false;
									continue;
								}
							}
						}
						c.setChassis(name);

					} else if (j == 4 ) {
						if(!name.equals("null") && !name.equals("1"))
							c.setOrderNumber(name);
					} else if (j == 5) {
						if(!name.equals("null") && !name.equals("1")){
							try {
								double dou = Double.valueOf(name).doubleValue();
								c.setSupplyPrice(dou);
							} catch (Exception e) {
								this.addActionError("第" + (i + 1) + "行，第" + (j + 1)+ "列," + name + "供货价数据错误\n");
								mark = false;
								continue;
							}
						}
					} else if (j == 6) {
						if(!name.equals("null") && !name.equals("1"))
							c.setDraft(name);
						
					} else if (j == 7) {
						if (!name.equals("null") && !name.equals("1")) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							try {
								Date date = sdf.parse(name);
								c.setGoingOutDate(date);
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,出门日:  " + name+ "  数据错误\n");
								mark = false;
								continue;
							}
						} else {
							c.setGoingOutDate(null);
						}
					} else if (j == 8) {
						if (!name.equals("null") && !name.equals("1")) {
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd");
							try {
								Date date = sdf.parse(name);
								c.setScheduledDate(date);
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,预定到店日:  " + name+ "  数据错误\n");
								mark = false;
								continue;
							}
						} else {
							this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,预定到店日日期:  " + name+"  不能为空\n");
							mark = false;
							continue;
						}
					} else if (j == 9) {
						if (!name.equals("null") && !name.equals("1")) {

							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							try {
								Date date = sdf.parse(name);
								c.setDepartDate(date);
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,发车信息日期:  " + name+"  数据错误\n");
								mark = false;
								continue;
							}
						} else {
							c.setDepartDate(null);
						}

					} else if ((j + 1) != row.size() && j < 10 ) {
						this.addActionError("第" + (i + 1) + "行，第" + (j + 1) + "列,数据错误或者不能为空\n");
						mark = false;
						continue;
					}
					if ((j + 1) == row.size()) {
						if (name.equals("1")) {
							c.setChange(true);
						} else {
							c.setChange(false);
							
						}

					}

				}
				if(boo){
					if (mark) {
						boolean bo = true;
						for(Iterator<Brand> iterator = c.getShop().getBrands().iterator(); iterator.hasNext();){
							Brand brand = iterator.next();
							if(brand.getId().equals(getBrand().getId())){
								bo = false;
							}
						}
						if(bo){
							this.addActionError(c.getShop().getShopName()+"  与      "+brandService.find(getBrand().getId()).getName()+"   没有关联，请核对数据\n");
							mark = false;
							continue;
						}
						c.setBrand(getBrand());
						c.setBatchNumber(batchNum);
						c.setFinancial(getFinancial());
						c.setCreateDate(new Date());// 添加创建时间
						c.setCmImporting(CopyOfCertificationImporting.YES);// 添加是否为导入标示
						c.setState(CertificationType.ONORDER);// 添加合格证状态
						if(bool){
							certifications.add(c);
						}else{
							listC.add(c);
						}
						
					}
				}else{
					boo=true;
					ms = false;
				}
				
				
			}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			this.addActionError("文件不匹配, 请确认导入文件是合格证导入文件\n");
			 mark = false;
	
		}
		int mr=0;//没有覆盖的记录条数
		int fu = 0;//覆盖的记录条数
		String mString="";
		if (mark) {
			for (int i = 0; i < listC.size(); i++) {
				Certification cf = listC.get(i);
				try {
					cfService.save(cf);
					mr+=1;
				} catch (Exception e) {
					mString += "  \n店号为："+cf.getShop().getShopMark()+"  数据导入失败";
				}
				
			}
			for (int i = 0; i < certifications.size(); i++) {
				Certification cf = certifications.get(i);
				Certification certification = certificationMap.get(cf.getChassis());
				Workflow workflow = workflowService.find(WorkflowType.ADD, certification.getId());
				if(null != workflow){
					String msg = "由于 " + getUser().getRealName() + "的导入，车架号为："+certification.getChassis()+"更改状态为在途";
					workflowService.audit(getUser(), workflowService.find(WorkflowType.ADD, certification.getId()), WorkflowState.FINISH, WorkflowOperateType.PASS,msg );
				}
				
				try {
					String[] ary=new String[]{"id","createdAt","creator"};
					BeanUtils.copyProperties(cf,certification, ary);
					cf.setId(certification.getId());
					cf.setCreatedAt(certification.getCreatedAt());
					cf.setCreator(certification.getCreator());
					cfService.save(certification);
					fu += 1;
				} catch (Exception e) {
					mString += "  \n店号为："+cf.getShop().getShopMark()+"  数据导入失败";
				}
				
			}
			String m="新增数据成功\n    应导入数据："+listC.size()+"   实际导入："+mr+mString+"\n"+"覆盖更新:  "+fu+" 条";
			setSuccessPopMessage(m);
			if(ms){
				brandList = brandService.seleteAll();
				fiList = financialService.finList();
				setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
				reaklMsg =m;
				return "import";
				
			}else{
				brandList = brandService.seleteAll();
				fiList = financialService.finList();
				setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
				reaklMsg =m;
				return "import";
			}
			
		} else {
			brandList = brandService.seleteAll();
			fiList = financialService.finList();
			setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
			return "import";
		}

	}
	
	/**
	 * 获取EXCEL所有车架号
	 * 
	 * @param datas
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List<String> findUniqueChassises(List<List> datas) {
		List<String> chassises = new ArrayList<String>();
		if(datas != null){
			for (Iterator<List> iterator = datas.iterator(); iterator.hasNext();) {
				List<List> rowRecord = iterator.next();
				Object value = rowRecord.get(3);
				if(value != null && StringUtils.isNotBlank(value.toString())){
					chassises.add(value.toString());
				}
			}
		}
		return chassises;
	}

	/**
	 * 库存查询
	 * @return
	 */
	@Action("storageIndex")
	public String storageIndex(){
		brandList = brandService.findAll();
		fiList = financialService.findAll();
		Long fId = null;
		if(financial != null){
			fId = financial.getId();
		}
		User user = null;
		if(StringUtils.isNotBlank(userName))
		{
			user = userService.getUserByProperty("realName", userName);
		}
//		if(null != shopDTO){
//			setShopUserName(shopDTO.getShopName());
//		}
		if(StringUtils.isNotBlank(markShop)){
			if(shopDTO == null){
				shopDTO = new Shop();
			}
			shopDTO.setShopName(markShop);
			 
		}
		
		setPage(shopService.findKucun(shopDTO,brand, this.getCurrentPage(), this.getPageSize(), fId, user,getUser()));
		return "storageIndex";
	}
	
	@Action("seleteTreaty")
	public String seleteTreaty(){
		shopSc=shopService.find(shopIdLong);
		treaties=treatyService.treatieList(shopIdLong);
		setRedirectUrl("storageIndex.do?currentPage=" + getCurrentPage(), "shopDTO", shopDTO);
		return "seleteTreaty";
	}
	/*
	 * 获得区域经理名字
	 */
	public String getShopUserName(Long shopId){
		StringBuilder names = new StringBuilder();
		List<Organization> orgs = organizationService.findUserDomainByShopId(shopId);
		if(orgs != null && orgs.size() > 0){
			for (Iterator<Organization> iterator = orgs.iterator(); iterator.hasNext();) {
				Organization org = iterator.next();
				String name = userService.selectName(org.getObjectId());
				if(StringUtils.isNotBlank(name)){
					names.append(org.getName());
					if(iterator.hasNext()){
						names.append(",");
					}
				}
				
			}
		}
		return names.toString();
	}
	/*
	 * 获得驻店员名字
	 */
	public String findUserShopByShopId(Long shopId){
		StringBuilder names = new StringBuilder();
		List<Organization> orgs = organizationService.findUserShopByShopId(shopId);
		if(orgs != null && orgs.size() > 0){
			for (Iterator<Organization> iterator = orgs.iterator(); iterator.hasNext();) {
				Organization org = iterator.next();
				names.append(org.getName());
				if(iterator.hasNext()){
					names.append(",");
				}
			}
		}
		return names.toString();
	}


	/** 合格证列表 */
	@Action(INDEX)
	public String index() {
		if(search == null){
			search = new CertificationDTO();
			search.setChange(true);
		}
		fiList = financialService.finList();
		brandList = brandService.findAll();
		setPage(cfService.findPage(search, this.getCurrentPage(),this.getPageSize()));
		if(search!=null&&search.getReleaseOnly()!=null&&search.getReleaseOnly()==1)
			return "releaseIndex";
		else
			return INDEX;
	}
	
	/** 待释放合格证列表 */
	@Action("releaseIndex")
	public String releaseIndex() {
		if(search==null)
			search=new CertificationDTO();
		search.setReleaseOnly(1);
		setPage(cfService.findPage(search, this.getCurrentPage(),
				this.getPageSize()));
		return "releaseIndex";
	}
	
	/** 确认收证*/
	@Action("preReceive")
	public String preReceive() {
		cerF=cfService.find(id);
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(),"search", search);
		return "receive";
	}
	
	/** 确认收证*/
	@Action("receive")
	public String receive() {
		Certification cf=cfService.find(cerF.getId());
		cf.setCertificationNum(cerF.getCertificationNum());//合格证号
		cf.setChassis(cerF.getChassis());//车架号
		cf.setDraftBeginDate(cerF.getDraftBeginDate());//（汇票）贷款起始日
		cf.setDraftEndDate(cerF.getDraftEndDate());
		cf.setWarehouseDate(new Date());
		cf.setState(CertificationType.INSTOCK);
		
		cfService.save(cf);
		setPage(cfService.findPage(search, this.getCurrentPage(),
				this.getPageSize()));
		setSuccessPopMessage("确认收证成功");
		return SHOW_MSG_PAGE;
	}

	/** 弹出框选择合格证 */
	@Action("choose")
	public String choose() {
		if(search==null)
			search=new CertificationDTO();
		search.setChoose(true);
		if(CommonUtil.isNotEmpty(ids)&&ids.endsWith(",")){
			ids=ids.substring(0,ids.length()-1);
		}
		if(CommonUtil.isNotEmpty(vals)&&vals.endsWith(",")){
			vals=vals.substring(0,vals.length()-1);
		}
		System.out.println(indexA);
		setPage(cfService.findPage(search, this.getCurrentPage(),this.getPageSize()));
		return "choose";
	}
	
	public Integer getcreInet(Long shopId){
		return cfService.getcreInet(shopId);
	}
	/** 根据协议取出相对应的金融机构 */
	@Action("shopFinal")
	public String shopFinal(){
//		Shop shop = shopService.find(shopIdLong);
		
		List<String> list =new ArrayList<String>();
		List<Treaty> treaties = treatyService.treatyList(shopIdLong);
		String text = "";
		if(null != treaties){
			if(treaties.size()>0){
				for(Treaty treaty : treaties){
					if(text.indexOf(treaty.getFinancial().getName())==-1){
						String texta = treaty.getFinancial().getId()+":"+treaty.getFinancial().getName();
						text += treaty.getFinancial().getId()+":"+treaty.getFinancial().getName();
						list.add(texta);
					}
				}
			}
			if(list.size()>0){
				Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
				this.setJsonText(gson.toJson(list));
			}else{
				Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
				this.setJsonText(gson.toJson(null));
			}
			
		}
		return JSON_PAGE;
	}
	@Action("detailsBrand")//查询默认渠道
	public String detailsBrand() {
		Shop shop = shopService.find(shopIdLong);
		String text = "";
		List list =new ArrayList();
			if(shop!=null && shop.getBrands().size()>0){
				for(Brand brand : shop.getBrands()){
					if(text.indexOf(brand.getName())==-1){
						String texta=brand.getId()+":"+brand.getName();
						text+=brand.getId()+":"+brand.getName();
						list.add(texta);
					}
				}
			}
			if(list.size()>0){
				Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
				this.setJsonText(gson.toJson(list));
			}else{
				Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
				this.setJsonText(gson.toJson(null));
			}
		return JSON_PAGE;
	}
	
	/** 合格证释放 */
	/*@Action("release")
	public String release() {
		if (id != null) {
			cfService.release(id);
			setSuccessPopMessage("合格证释放成功");
			if (getRedirectUrl() == null)
				setRedirectUrl("releaseIndex.do?currentPage=" + getCurrentPage(),"search", search);
			return SHOW_MSG_PAGE;
		}
		setSuccessPopMessage("未找到相关合格证,请重新尝试");
		if (getRedirectUrl() == null)
			setRedirectUrl("releaseIndex.do?currentPage=" + getCurrentPage(),
					"search", search);
		return SHOW_MSG_PAGE;

	}*/
	
	/**
	 * 合格证详情
	 * @return
	 */
	@Action("cfView")
	public String cfView() {
		entity = cfService.find(id);
		recordReturn = recordReturnService.fianCertifiList(id);
		return "cfView";
	}

	public CertificationDTO getSearch() {
		return search;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void setSearch(CertificationDTO search) {
		this.search = search;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Integer getCaozuo() {
		return caozuo;
	}

	public void setCaozuo(Integer caozuo) {
		this.caozuo = caozuo;
	}

	public Certification getCre() {
		return cre;
	}

	public void setCre(Certification cre) {
		this.cre = cre;
	}

	public Certification getCer() {
		return cer;
	}

	public void setCer(Certification cer) {
		this.cer = cer;
	}

	public List<Shop> getShopList() {
		return shopList;
	}

	public void setShopList(List<Shop> shopList) {
		this.shopList = shopList;
	}

	public Shop getShopDTO() {
		return shopDTO;
	}

	public void setShopDTO(Shop shopDTO) {
		this.shopDTO = shopDTO;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public Shop getShopSc() {
		return shopSc;
	}

	public void setShopSc(Shop shopSc) {
		this.shopSc = shopSc;
	}

	public List<Treaty> getTreaties() {
		return treaties;
	}

	public void setTreaties(List<Treaty> treaties) {
		this.treaties = treaties;
	}

	public List<Brand> getBrandList() {
		return brandList;
	}

	public void setBrandList(List<Brand> brandList) {
		this.brandList = brandList;
	}

	public List<Financial> getFiList() {
		return fiList;
	}

	public void setFiList(List<Financial> fiList) {
		this.fiList = fiList;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public Brand getBrand() {
		return brand;
	}

	public void setBrand(Brand brand) {
		this.brand = brand;
	}

	public Financial getFinancial() {
		return financial;
	}

	public void setFinancial(Financial financial) {
		this.financial = financial;
	}

	public Certificate getC() {
		return c;
	}

	public void setC(Certificate c) {
		this.c = c;
	}

	public Long getShopIdLong() {
		return shopIdLong;
	}

	public void setShopIdLong(Long shopIdLong) {
		this.shopIdLong = shopIdLong;
	}

	public Certification getCerF() {
		return cerF;
	}

	public void setCerF(Certification cerF) {
		this.cerF = cerF;
	}

	public WorkflowService getWorkflowService() {
		return workflowService;
	}

	public void setWorkflowService(WorkflowService workflowService) {
		this.workflowService = workflowService;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	/*
	 * 导入合格证---------------------数据迁移
	 */
	@SuppressWarnings("rawtypes")
	@Action("importSearchMove")
	public String importSearchMove() {

		List<Shop> shops =shopService.findAll();//获得所有的销售店
		Map<String, Organization> map = organizationService.organizationShopMap();//获得所有组织架构上的  销售店数据
		Map<String,Treaty> treatyFinancialMap = treatyService.getTreatyAllMap(true);//获得所有有效地 协议     键   为金融机构的  名称
//		Map<String,Treaty> treatyShopMap = treatyService.treatyAllMap(false);//获得所有有效地 协议     键   为销售店的  名称
		Map<String, Brand> brandMap = brandService.brandMap();//获得所有的 渠道
		Map<String, Financial> financialMap = financialService.financialAllMap();//获得所有的金融机构
		List<Certification> listC = new ArrayList<Certification>();//记录不需要覆盖跟新的合格证
		boolean mark = true;
		
		
		Certification c = null;
		ExcelSheetParser parser;
		try {
			parser = new ExcelSheetParser(file);
			List<List> datas = parser.getDatasInSheet();
			
			List<String>[] uniques = this.findUniques(datas);
			Map<String, Certification> certificationMapNot = cfService.certificationMapNot(uniques[0]);//除 暂存 ，在途，待审核，未通过 的所有合格证
			Map<String, Certification> certificationNumMap = cfService.certificationNumMapNot(uniques[1]);//所有合格证号
			Map<String, Certification> certificationMap = cfService.certificationChassisEq(uniques[0]);//暂存 ，在途，待审核，未通过 的所有合格证
			 for(int i = 0 ; i < datas.size(); i++){//获得每行数据
				   List row = datas.get(i);
				   Shop shop = null;
				   c = new Certification();
				   for (int j = 0; j < row.size(); j++) {
				    Object value = row.get(j);
				    String name = String.valueOf(value);
				    name = name.trim();
				    
					if (j == 0 && !name.equals("null")) {
						name = name.toUpperCase();
						for(Shop s : shops){
//							boolean bo = false;
							if(s.getShopMark().equals(name)){// 查找店号是否在库
								shop = s;
								break;
							}
						}
						if (shop != null) {
							c.setShop(shop);
						} else {
							this.addActionError("第" + (i + 2) + "行，第" + (j + 1) + "列," + name + "店号不存在\n");
							mark = false;
							continue;
						}
					} else if (j == 1 && !name.equals("null")) {
						if (shop != null) {
//							if (!shop.getShopName().equals(name)) {// 判断店号
//																	// 店名是否匹配
//								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,店名:" + name + "  与 店号: "+ shop.getShopMark() + "  不匹配\n");
//								mark = false;
//								continue;
//							}
							if(null != map && (map.containsKey(name) || map.containsKey(shop.getShopName()))){
								
							}else{
								this.addActionError("第" + (i + 2) + "行，第" + (j + 1) + "列,店名:" + name + " 没有存在组织架构上\n");
								mark = false;
								continue;
							}
						}
					} else if (j == 2 && !name.equals("null")) {                       //--------------------------------------渠道
						if(brandMap.containsKey(name)){//验证是否存在此主机厂
							Brand brand = brandMap.get(name);
//							System.out.println(brand.getName());
							c.setBrand(brand);
						}else{
							this.addActionError("第" + (i + 2) + "行，第" + (j + 1) + "列,渠道:\"" + name + "\" 没有存在系统中\n");
							mark = false;
							continue;
						}
					} else if (j == 3 && !name.equals("null")) {						//--------------------------------------金融机构
						if(financialMap.containsKey(name)){//验证是否存在此金融机构
//							System.out.println(row.get(5));
//							if("LVGDC46A0DG454002".equals(row.get(5).toString())){
//								System.out.println("LVGBH51K7DG085881");
//							}
							if(c.getShop() != null && treatyFinancialMap.containsKey(c.getShop().getShopName()+"-"+name)){//验证是否存在此金融机构的协议
								 
							}else{
								if(c.getShop() != null){
									this.addActionError("第" + (i + 2) + "行，第" + (j + 1) + "列,金融机构:" + name + " 与  "+c.getShop().getShopName()+" 没有任何有效地的协议\n");
								}
								mark = false;
								continue;
							}
							Financial financial = financialMap.get(name);
//							System.out.println(financial.getName());
							c.setFinancial(financial);
						}else{
							this.addActionError("第" + (i + 2) + "行，第" + (j + 1) + "列,金融机构:" + name + " 没有存在系统中\n");
							mark = false;
							continue;
						}
					}else if (j == 4 && !name.equals("null")) {                       //--------------------------------------合格证号
						name = name.toUpperCase();
						if(name.length()!=15){
							this.addActionError("第" + (i + 2) + "行，第" + (j + 1) + "列, " + name + "：合格证号不符合规范\n");
							mark = false;
							continue;
						}
						if (null != certificationNumMap && certificationNumMap.containsKey(name)) {// 判断合格证号是否已在库
							this.addActionError("第" + (i + 2) + "行，第" + (j + 1)+ "列, " + name + "：合格证号已存在\n");
							mark = false;
							continue;
						} else {
							for (int p = 0; p < listC.size(); p++) {// 判断导入文件是否存在相同的车架号
								Certification cfation = listC.get(p);
								if (cfation.getCertificationNum() == name) {
									this.addActionError("导入文件中 第" + name+ "：合格证号重复\n");
									mark = false;
									continue;
								}
							}
						}
						c.setCertificationNum(name);
					} else if (j == 5 && !name.equals("null")) {                       //--------------------------------------车架号
						name = name.toUpperCase();
						if(name.length()!=17){
							this.addActionError("第" + (i + 2) + "行，第" + (j + 1) + "列, " + name + "：车架号不符合规范\n");
							mark = false;
							continue;
						}
						if (null != certificationMapNot && (certificationMapNot.containsKey(name) || certificationMap.containsKey(name))) {// 判断车架号是否已在库
							this.addActionError("第" + (i + 2) + "行，第" + (j + 1)+ "列, " + name + "：车架号已存在\n");
							mark = false;
							continue;
						} else {
							for (int p = 0; p < listC.size(); p++) {// 判断导入文件是否存在相同的车架号
								Certification cfation = listC.get(p);
								if (cfation.getChassis() == name) {
									this.addActionError("导入文件中 第" + name+ "：车架号重复\n");
									mark = false;
									continue;
								}
							}
						}
						c.setChassis(name);
					} else if (j == 6 ) {                        //--------------------------------------发动机号
						if("null".equals(name)){
							   name = null;
						   }
						c.setEngine(name);
					
					} else if (j == 7 ) {                        //--------------------------------------车型
						if("null".equals(name)){
							   name = null;
						   }
						c.setMotorcycleType(name);
					
					} else if (j == 8 ) {                        //--------------------------------------订单号
						if("null".equals(name)){
							   name = null;
						   }
						c.setOrderNumber(name);
					 
					} else if (j == 9 ) {                        //--------------------------------------汇票号
						if("null".equals(name)){
							   name = null;
						   }
						c.setDraft(name);
					 
					} else if (j == 10 ) {                       //--------------------------------------汇票号开始时间
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						if("null".equals(name)){
							   name = null;
						   }
						if(StringUtils.isNotBlank(name)){
							try {
								Date date = sdf.parse(name);
								c.setDraftBeginDate(date);//----------------------------
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,汇票号开始日期:  " + name+"  数据错误\n");
								mark = false;
								continue;
							}
						}
						
						
					} else if (j == 11 ) {                       //--------------------------------------汇票号结束时间
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						if("null".equals(name)){
							   name = null;
						   }
						if(StringUtils.isNotBlank(name)){
						try {
							Date date = sdf.parse(name);
							c.setDraftEndDate(date);//----------------------------
						} catch (ParseException e) {
							this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,汇票号结束日期:  " + name+"  数据错误\n");
							mark = false;
							continue;
						}
						}
						
					} else if (j == 12) {                       //--------------------------------------供货价
						if("null".equals(name)){
							   name = null;
						   }
						if(StringUtils.isNotBlank(name)){
							
						
						try {
							double dou = Double.valueOf(name).doubleValue();
							c.setSupplyPrice(dou);
						} catch (Exception e) {
							this.addActionError("第" + (i + 1) + "行，第" + (j + 1)+ "列," + name + "供货价数据错误\n");
							mark = false;
							continue;
						}
						}
						
					} else if (j == 13 ) {                          //--------------------------------------出门日
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						if("null".equals(name)){
							   name = null;
						   }
						if(StringUtils.isNotBlank(name)){
							try {
								Date date = sdf.parse(name);
								c.setGoingOutDate(date);//----------------------------
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,出门日期:  " + name+"  数据错误\n");
								mark = false;
								continue;
							}
						}
				    
				   } else if (j == 14 ) {                          //--------------------------------------预定到店日
					   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					   if(null == name || "null".equals(name) ){
						   this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,预定到店日日期:  " + name+"  不能为空\n");
							mark = false;
							continue;
					   }
						   if(StringUtils.isNotBlank(name)){
							try {
								Date date = sdf.parse(name);
								c.setScheduledDate(date);//----------------------------
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,预定到店日日期:  " + name+"  数据错误\n");
								mark = false;
								continue;
							}
					   }
					   
				   } else if (j == 15 ) {                          //--------------------------------------发车信息日期
					   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					   if("null".equals(name)){
						   name = null;
					   }
					   if(StringUtils.isNotBlank(name)){
							try {
								Date date = sdf.parse(name);
								c.setDepartDate(date);//----------------------------
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,发车信息日期:  " + name+"  数据错误\n");
								mark = false;
								continue;
							}
					   }
					   
				   } else if (j == 16 ) {                  //--------------------------------------备注
						   if("null".equals(name)){
							   name = null;
						   }
					   c.setRemarks(name);
					  
				   }else if (j == 17 ) {                       //--------------------------------------二网地址
					   if("null".equals(name)){
						   name = null;
					   }
					   c.setTheAddress(name);
						  
				   }else if (j == 18 ) {                       //--------------------------------------补录日期 
					   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					   if("null".equals(name)){
						   name = null;
					   }
					   if(StringUtils.isNotBlank(name)){
						   try {
								Date date = sdf.parse(name);
								c.setBuluDate(date);//----------------------------
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,补录日期 日期:  " + name+"  数据错误\n");
								mark = false;
								continue;
							}
					   }
						
							  
				   }else if (j == 19 && !name.equals("null")) {                       //--------------------------------------入库日期
					   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					   
					   if(StringUtils.isNotBlank(name)){
							try {
								Date date = sdf.parse(name);
								c.setWarehouseDate(date);//----------------------------
							} catch (ParseException e) {
								this.addActionError("第" + (i + 1) + "行，第"+ (j + 1) + "列,入库日期日期:  " + name+"  数据错误\n");
								mark = false;
								continue;
							}
					   }
						  
			      } else if ((j + 1) != row.size()) {
						this.addActionError("第" + (i + 1) + "行，第" + (j + 1) + "列,数据错误或者不能为空\n");
						mark = false;
						continue;
					}
					if ((j + 1) == row.size()) {
						if ("1".equals(name)) {
							c.setChange(true);
						} else {
							c.setChange(false);
						}

					}
					
			 }
				   c.setCmImporting(CopyOfCertificationImporting.YES);// 添加是否为导入标示
				   c.setState(CertificationType.INSTOCK);
				   listC.add(c);
			 }
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			this.addActionError("文件不匹配, 请确认导入文件是合格证导入文件\n");
			 mark = false;
		}
		try{
			if(mark){
				  if(listC.size()>0){
						for (Certification certification : listC) {
							cfService.save(certification);
						}
					}
				 
				  setSuccessPopMessage("导入成功");
				  
				  setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
					return SHOW_MSG_PAGE;
			  }
			
		}catch(Exception e){
			e.printStackTrace();
			setFailPopMessage("导入失败，请联系管理员");
			setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
			return SHOW_MSG_PAGE;
		}
		
		return "importSearchMove";
		  
		  //--------------------------------------------------------------------ss
		
	}	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List<String>[] findUniques(List<List> datas) {
		List[] uniques = new List[2];
		List<String> certifications = new ArrayList<String>(); 
		List<String> chassises = new ArrayList<String>();
		if(datas != null){
			for (Iterator<List> iterator = datas.iterator(); iterator.hasNext();) {
				List<List> rowRecord = iterator.next();
				Object value = rowRecord.get(4);
				if(value != null && StringUtils.isNotBlank(value.toString())){
					chassises.add(value.toString());
				}
				
				value = rowRecord.get(5);
				if(value != null && StringUtils.isNotBlank(value.toString())){
					certifications.add(value.toString());
				}
			}
		}
		
		uniques[0] = certifications;
		uniques[1] = chassises;
		
		return uniques;
	}

	@Action("openImportSearchMove")
	public String openImportSearchMove(){
		return "importSearchMove";
	}
	public String getuserName(String name){
		User use= userService.getUserByName(name);
		return use.getRealName();
	}

	public String getVals() {
		return vals;
	}

	public void setVals(String vals) {
		this.vals = vals;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public Integer getIndexA() {
		return indexA;
	}

	public void setIndexA(Integer indexA) {
		this.indexA = indexA;
	}
	/** 合格证释放回库 */
	@Action("recordReturn")
	public String recordReturn(){
		Certification certifi = cfService.get(id);
		RecordReturn recordReturn = new RecordReturn();
		
		recordReturn.setCerId(certifi.getId());
		recordReturn.setCertificationNum(certifi.getCertificationNum());
		recordReturn.setChassis(certifi.getChassis());
		recordReturn.setLeaveDate(certifi.getLeaveDate());
		recordReturn.setReturnDate(new Date());
		recordReturn.setUser(getUser().getRealName());
		recordReturn.setRemark(this.getReturnRemark());
		
		certifi.setState(CertificationType.INSTOCK);
		//清空释放单信息
		certifi.setRelease(null);
		certifi.setReleaseUser(null);
		certifi.setLeaveDate(null);
		
		recordReturnService.save(recordReturn);
		
		cfService.save(certifi);
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(),"search", search);
		setSuccessPopMessage("回库成功");
		return SHOW_MSG_PAGE;
	}

	public List<RecordReturn> getRecordReturn() {
		return recordReturn;
	}

	public void setRecordReturn(List<RecordReturn> recordReturn) {
		this.recordReturn = recordReturn;
	}

	/**
	 * 删除在库合格证
	 * 
	 * @return
	 */
	@Action("deleteInStock")
	public String deleteInStock(){
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search", search);
		try {
			Certification certification = cfService.find(id);
			if(certification != null){
				cfService.deleteInStock(certification);
				setSuccessPopMessage("删除成功");
			}else{
				setFailPopMessage("删除失败，合格证不存在。");
			}
			
			
		} catch (Exception e) {
			LOG.error("删除在库合格证失败", e);
			setSuccessPopMessage("删除失败。");
		}
		return SHOW_MSG_PAGE;
	}
	private String reaklMsg;

	public String getReaklMsg() {
		return reaklMsg;
	}

	public void setReaklMsg(String reaklMsg) {
		this.reaklMsg = reaklMsg;
	}
}
